$(function() {
    var cols=6;
	var rows_delete=0;
	var mode="add";
	var m_id=0;
    var url='controls/vehicle_model.php';
	var allFields = $( [] ).add( $("#txtDriver") )
							.add( $("#txtTel"))
							.add( $("#txtDetail"))
							.add( $("#txtCost"))
							.add( $("#txtRemark"))
							.add( $("#txtRoute"))
							.add( $("#txtTime"))
							.add( $("#txtDate"));
							
	$('.btndate').datepicker();
	
	$("#btnPrint").click(function(e){
		
		e.preventDefault(); 
		$("#frmBus").get(0).setAttribute('action', 'rpt_bus.php');
		 
		$("#frmBus").attr('target', '_blank').submit().removeAttr('target').removeAttr('action');
	
	});
	
	LoadData("","",0);
	
	 initialData();
	 
	 function initialData(){
		$.get(url, {"m": "term"}, function(data) {
			var obj = eval('(' + data + ')');
			if (obj != null) {
				$.each(obj, function(index, text) {
					$("#txtTerm_Search,#txtTerm").append(
							$('<option></option>').val(index).html(text)
							);
				$.get(url,{"m":"currterm"},function(data){
					$("#txtTerm_Search,#txtTerm").val(data);
				});
			});
        }
		});
	 
		$.get(url, {"m":"year"},function(data){
			var cboObj=eval('('+data+')');	
			if (cboObj != null){
				$.each(cboObj, function(index, text) {
					$("#cboYear,#cboYear_Search").append(
						$('<option></option>').val(text).html(text)
					);
				});
				$.get(url,{"m":"curryear"},function(data){
					$("#cboYear,#cboYear_Search").val(data);
				});
			}
		 
		});
		
	 	$.get(url, {"m":"cbo_car"},function(data){
			var cboObj=eval('('+data+')');	
			var cnt=0;
			if (cboObj != null){
				$.each(cboObj, function(index, text) {
					if (cnt==0){
						LoadCBODetail(index);
					}
					$("#cboCarType").append(
						$('<option></option>').val(index).html(text)
					);
					 cnt++;
				});
			}
		});
		
		$.get(url, {"m":"feeType"},function(data){
			var cboObj=eval('('+data+')');	
			if (cboObj != null){
				$.each(cboObj, function(index, text) {
					$("#cboPayDue").append(
						$('<option></option>').val(index).html(text)
					);
				});
			}
		});
	 }
	 $("#btnSearch").click(function(){
		var _y = $("#cboYear_Search").val();
		var _t = $("#txtTerm_Search").val();
		var _s = $("#cboStatus").val();
		
		LoadData(_y,_t,_s);
	 });
	 function LoadData(year,term,status){
        $( "#resultData tbody tr" ).remove();
 
        
        $('#resultData').dataTable( {
			"bProcessing": true,
			"bFilter": false,
			"bAutoWidth": false,
			"bLengthChange": false,
			"sAjaxSource": url,
			"oLanguage": {
				"sEmptyTable":     "ไม่พบข้อมูล"
			},
			"bDestroy": true,
			"sServerMethod": "POST",
			"fnServerParams": function ( aoData ) {
					aoData.push( { "name": "m", "value": "load_manage" },
								{"name":"y","value":year},
								{"name":"t","value":term},
								{"name":"s","value":status}
							);
				},
			"aoColumnDefs":[
				{  "bVisible": false , "aTargets": [ 1 ] },	
				{   "bSortable": true, "aTargets": [ 2 ] ,"sClass":"left"},	
				{   "bSortable": true, "aTargets": [ 3 ] ,"sClass":"center" },	
				{   "bSortable": true, "aTargets": [ 4 ] ,"sClass":"center" },	
				{   "bSortable": true, "aTargets": [ 5 ] ,"sClass":"center" },	
				{   "bSortable": true, "aTargets": [ 6 ] ,"sClass":"center" },	
				{   "bSortable": true, "aTargets": [ 7 ], "sClass":"center",
					"mRender": function ( data, type, full ) {
						var tmp="";
						if (data=='Y')
							tmp="<span class='label label-success'>ใช้งาน</span>";
						else
							tmp="<span class='label label-warning'>ยกเลิก</span>";
						return tmp;}
				},
				{ "aTargets": [ 8 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
					if (_te==1) 
						return "<a href='#popup' data-toggle='modal'><img src='img/edit-file.png' class='btnEdit' style='cursor:pointer;'/></a>";
					else
						return "";
					}
				},
				{"aTargets": [ 9 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
						if (_te==1) 
						return "<a href='#popupConfirm' data-toggle='modal'><img src='img/delete-file.png' class='btnDel' style='cursor:pointer;'/></a>";
						else 
						return "";
					}
				}
			],"fnDrawCallback": function ( oSettings ) {
				 
			/* Need to redo the counters if filtered or sorted */
			     var oSettings = this.fnSettings();
                 var iTotalRecords = oSettings.fnRecordsTotal();
				//alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);
				 
					if (iTotalRecords > 0){ 	
						if ( oSettings.bSorted || oSettings.bFiltered )
						{
							for ( var i=0, iLen=iTotalRecords ; i<iLen ; i++ )
							{
								$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
							}
						}
					}
				} 
		 } );
		 
      }

	 function LoadCBODetail(id){
		$.get(url, {"m":"c","i":id},function(data){
			var obj=eval('('+data+')');	
			 $("#txtDetail").val(obj['detail']);
		});
	 }
	
	function checkControl() {
        var bln = true;
        if ($("#txtRoute").val() == "" ) {
            $("#txtRoute").attr('style', "background-color:#fddedb;border:1px solid #f99891");
            bln = bln && false;
        } else {
            $("#txtRoute").removeAttr('style');
            bln = bln && true;
        }
        if ($("#txtTime").val() == "") {
            $("#txtTime").attr('style', "background-color:#fddedb;border:1px solid #f99891");
            bln = bln && false;
        } else {
            $("#txtTime").removeAttr('style');
            bln = bln && true;
        }
		if ($("#txtDate").val() == "") {
            $("#txtDate").attr('style', "width:100px;background-color:#fddedb;border:1px solid #f99891");
            bln = bln && false;
        } else {
            $("#txtDate").removeAttr('style');
			$("#txtDate").attr('style', "width:100px;");
            bln = bln && true;
        }
        return bln;
    }
	
	$("#btnAddCar").live('click',function(){
			
			if (checkControl()){
                $("#Error").css('display', 'none');
        
				var _route = $("#txtRoute").val();
				var _time = $("#txtTime").val();
				var _date = $("#txtDate").val();
					//alert(typeName);
					$("#table_detail").dataTable().fnAddData([
						0, _route, _time, _date
					]);
			}else{
						  
                $("#Error").css('display', '');
                return;
			}
			
			$("#txtRoute,#txtTime,#txtDate").val('');
			
			
	});
	
	$("#cboCarType").change(function(){
		var cid=$(this).val();
		LoadCBODetail(cid);
	});
	
	$("#btnConfirm").live('click',function(){
		$("input").not("[type=submit]").jqBootstrapValidation({preventSubmit: false,
			submitSuccess: function ($form, event) { event.preventDefault();}
		}); 
	  
		var _year = $.trim($("#cboYear").val());		
		var _term = $("#txtTerm").val();
		var _driver = $("#txtDriver").val();
		var _telephone = $("#txtTel").val();
		var _due = $("#cboPayDue").val();
		var _cost = $("#txtCost").val();
		var _carid = $("#cboCarType").val();
		var _remark = $("#txtRemark").val();
		var _detail = $("#txtDetail").val();
		var dataSet;
		var list = [];
		var rows = $('#table_detail').dataTable().fnGetNodes();

		for (var i = 0; i < rows.length; i++)
		{
			var row_data = $('#table_detail').dataTable().fnGetData(rows[i]);
			list.push({'route': row_data[1],
				'route_time': row_data[2],
				'start_date1': row_data[3]});
		}

		
		if (mode=="add"){
			dataSet={"m":"add_detail","list":list,"year":_year,"term":_term ,"driver":_driver,"telephone":_telephone,"cost_type":_due,"cost":_cost,"car_id":_carid,"remark":_remark,"detail":_detail,"status":$('input[name=chk]:checked').val()};  
			
		}else{
			dataSet={"m":"edit_detail","id":m_id,"list":list,"year":_year,"term":_term ,"driver":_driver,"telephone":_telephone,"cost_type":_due,"cost":_cost,"car_id":_carid,"remark":_remark,"detail":_detail,"status":$('input[name=chk]:checked').val()};  
		}
		 
		if (list!=""){
			$.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: dataSet,
				success: function(data){
					$("#popup").modal('hide');
					LoadData("","",0);
					//allFields.val("");
				}
			});
			
		}
		 $("input").jqBootstrapValidation("destroy");
		 mode="";
		
	});		
 
	
	 $(".txtamt").keypress(function(e){
		
		if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
			return false;
		}
	});
	
		
	if (_dd==1){
		$("#btnAdd").show();
	}else{
		$("#btnAdd").hide();
	}
	 
	$("#btnAdd").live('click', function(){
		mode="add";
		$("#Error").css('display', 'none');
		allFields.val("");
			 
		SetTableDetail(0);
	});
		
	//Popup confirm delete
	$(".btnDel").live('click',function(){
		var rows = $(this).closest("tr").get(0);
		rows_delete = $('#resultData').dataTable().fnGetPosition(rows);

	}); 
	
	$("#btnDelete").live('click', function(){
		var row_id =$('#resultData').dataTable().fnGetData(rows_delete);
		
		var id=row_id[1];
		 
		 $.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":"delCar","id":id},
				 success: function(data){
					$("#popupConfirm").modal('hide');
					$('#resultData').dataTable().fnDeleteRow( rows_delete );
					$('#resultData').dataTable().fnDraw();
				 }
			 });
 
	}); 
	
	$(".btnEdit").live('click',function(){
		mode="edit";
		var rows = $('#resultData').dataTable().fnGetPosition($(this).closest("tr").get(0));
		var data =$('#resultData').dataTable().fnGetData(rows);
		 
		m_id = data[1];
	   SetTableDetail(m_id);
		 
		$.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":"detail","id":m_id},
				 success: function(data){
				 
					var obj = eval('(' + data + ')');
					$("#cboYear").val(obj['year']);		
					$("#txtTerm").val(obj['term']);
					$("#txtDriver").val(obj['driver']);
					$("#txtTel").val(obj['telephone']);
					$("#cboPayDue").val(obj['cost_type']);
					$("#txtCost").val(obj['cost']);
					$("#cboCarType").val(obj['car_id']);
					$("#txtRemark").val(obj['remark']);
					$("#txtDetail").val(obj['cost_detail']);
					
					if (obj['status']=='Y'){
						$("#chkY").attr('checked','checked');
					}else{
						$("#chkN").attr('checked','checked');
					}
				 }
			 });
	});
	$(".btnDel_detail").live('click', function() {
        var rows = $(this).closest("tr").get(0);
        rows_delete = $('#table_detail').dataTable().fnGetPosition(rows);
        $('#table_detail').dataTable().fnDeleteRow(rows_delete);
        $('#table_detail').dataTable().fnDraw();
    });
	function SetTableDetail(id) {
		 
        $("#table_detail").dataTable({"bProcessing": true,
            "bFilter": false,
            "bInfo": false,
            "bPaginate": false,
            "bLengthChange": false,
            "sAjaxSource": url,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
            "fnServerParams": function(aoData) {
                aoData.push({"name": "m", "value": "load_car"},
							{"name": "id", "value": id}             
				);
            },
            "aoColumnDefs": [
                {"bSortable": true, "aTargets": [1], "sClass": "center"},
                {"bSortable": true, "aTargets": [2], "sClass": "text-left"},
                {"bSortable": true, "aTargets": [3], "sClass": "center"},
                {"aTargets": [4],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
                        
                            return "<a href='#'  ><img src='img/delete-file.png' class='btnDel_detail' style='cursor:pointer;'/></a>";
                       
                    }
                }

            ], "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = iTotalRecords; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }

            }

        });

    }
	  
    
});


